package com.example.yzj16478026.utils;


import android.content.Context;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * 操作reg.properties文件的类
 */
public class PropertiesUtils {
    /**
     * 初始化将reg.properties文件装载到输入流中
     */
    private static FileInputStream inputStream=null;
    private static FileOutputStream outputStream=null;
    private static Properties regProperties=null;
    private static final String fileName="reg.properties";
    static {
        init(ContextUtil.getInstance());
    }

    private static void init(Context context) {
        regProperties=new Properties();
        try {
            inputStream=ContextUtil.getInstance().openFileInput(fileName);
            regProperties.load(inputStream);
            outputStream=ContextUtil.getInstance().openFileOutput(fileName,Context.MODE_PRIVATE);
            regProperties.store(outputStream,null);
            inputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过注册名获取密码
     * @param RegName
     * @return
     */
    public static String getPwdForRegName(String RegName){
        try {
            inputStream=ContextUtil.getInstance().openFileInput(fileName);
            regProperties.load(inputStream);
            String pwd=regProperties.getProperty(RegName);
            if (pwd!=null){
                inputStream.close();
                return pwd;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加一个用户
     * @param username
     * @param password
     */
    public static int putUser(String username,String password){
        try {
            outputStream=ContextUtil.getInstance().openFileOutput(fileName,Context.MODE_PRIVATE);
            if (getPwdForRegName(username)!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return -1;
            }else {
                regProperties.setProperty(username, password);
                try {
                    regProperties.store(outputStream, null);
//                    outputStream.flush();
                    outputStream.close();
                    return 1;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
